import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler
} from '@nestjs/common'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { Response } from '../interfaces/response.interface'

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map((data) => {
        // 处理自定义消息和数据
        let message = '操作成功'
        let resultData = data

        // 如果返回的数据中包含message字段，则使用该message
        if (data && typeof data === 'object' && 'message' in data) {
          message = data.message
          // 如果同时包含其他数据，则提取出来
          if ('user' in data || 'data' in data) {
            resultData = data.user || data.data || resultData
            delete resultData.message
          }
        }

        return {
          data: resultData,
          message: message,
          success: true
        }
      })
    )
  }
}
